import json
from rest_framework.status import HTTP_200_OK
from rest_framework.compat import (
    INDENT_SEPARATORS, LONG_SEPARATORS, SHORT_SEPARATORS
)
from rest_framework.renderers import JSONRenderer as JSONRendererRaw


class JSONRenderer(JSONRendererRaw):
    # 重构render方法
    def render(self, data, accepted_media_type=None, renderer_context=None):
        """
        Render `data` into JSON, returning a bytestring.
        """
        if data is None:
            return b''

        renderer_context = renderer_context or {}
        indent = self.get_indent(accepted_media_type, renderer_context)

        if indent is None:
            separators = SHORT_SEPARATORS if self.compact else LONG_SEPARATORS
        else:
            separators = INDENT_SEPARATORS

        if isinstance(data, dict):
            api_code = data.pop('code') if 'code' in data else HTTP_200_OK
            api_msg = data.pop('message') if 'message' in data else 'success'
            api_data = data.pop('data') if 'data' in data else data
            response = {
                'code': api_code,
                'message': api_msg,
                'data': api_data
            }
        else:
            response = {
                'code': HTTP_200_OK,
                'message': 'success',
                'data': data
            }

        ret = json.dumps(
            response, cls=self.encoder_class,
            indent=indent, ensure_ascii=self.ensure_ascii,
            allow_nan=not self.strict, separators=separators
        )

        # We always fully escape \u2028 and \u2029 to ensure we output JSON
        # that is a strict javascript subset.
        # See: http://timelessrepo.com/json-isnt-a-javascript-subset
        ret = ret.replace('\u2028', '\\u2028').replace('\u2029', '\\u2029')
        return ret.encode()
